package com.yeyks.common.utils.webutil;

import com.yeyks.common.config.CnBookingConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import sun.misc.BASE64Decoder;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

/**
 * AES加密信息 （Base64）
 *
 * @author Administrator
 */
@Slf4j
public class AesEncoderUtil {

    /**
     * 加密用的Key 可以用26个字母和数字组成 此处使用AES-128-CBC加密模式，key需要为16位。
     **/
    private static AesEncoderUtil instance = null;

    private AesEncoderUtil() {

    }

    public static AesEncoderUtil getInstance() {
        if (instance == null) {
            instance = new AesEncoderUtil();
        }
        return instance;
    }

    /**
     * 加密 固定 key 和 iv
     *
     * @param sSrc 数据（id）
     * @return
     */
    public String encrypt(String sSrc) {
        try {

            return convertEncryptSame(sSrc, CnBookingConfiguration.key, CnBookingConfiguration.iv);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }


    /**
     * 固定的 key 和 iv
     *
     * @param sSrc 数据(id)
     * @return
     */
    public String decrypt(String sSrc) {
        try {
            return convertDecryptSame(sSrc, CnBookingConfiguration.key, CnBookingConfiguration.iv);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    private static String convertEncryptSame(String encData, String secretKey, String vector) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        int blockSize = cipher.getBlockSize();
        byte[] dataBytes = encData.getBytes();
        int length = dataBytes.length;
        //计算需填充长度
        if (length % blockSize != 0) {
            length = length + (blockSize - (length % blockSize));
        }
        byte[] plaintext = new byte[length];
        //填充内容信息
        System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
        byte[] raw = secretKey.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
        IvParameterSpec iv = new IvParameterSpec(vector.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(plaintext);
        // 此处使用BASE64做转码。
        return Base64.encodeBase64String(encrypted);
    }

    private String convertDecryptSame(String sSrc, String sKey, String ivParameter) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IOException, IllegalBlockSizeException, BadPaddingException {
        byte[] raw = sKey.getBytes(StandardCharsets.US_ASCII);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        // 先用base64解密
        byte[] encrypted1 = Base64.decodeBase64(sSrc);
        byte[] original = cipher.doFinal(encrypted1);
        return new String(original, StandardCharsets.UTF_8).trim();
    }

    public static void main(String[] args) throws Exception {

        // 加密
        long lStart = System.currentTimeMillis();
        String enString = AesEncoderUtil.getInstance().encrypt("1403");
        log.info("===========加密后的字串是：{}===========", enString);

        long lUseTime = System.currentTimeMillis() - lStart;
        log.info("===========加密耗时：{}毫秒===========", lUseTime);
        // 解密
        lStart = System.currentTimeMillis();
        String deString = AesEncoderUtil.getInstance().decrypt(enString);
        log.info("===========解密后的字串是：{}==========", deString);
        lUseTime = System.currentTimeMillis() - lStart;
        log.info("===========解密耗时：{}毫秒=========", lUseTime);


        //jJ0TuXMllOZYQ8VpLC1xTg==
        ///XoHwq3UZsVgJ+hlfsMWLA==
    }

}
